package com.android.delivery;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;

import com.ada.common.widget.NoTouchViewPager;
import com.ada.common.widget.SpecialTab;
import com.alibaba.sdk.android.push.CloudPushService;
import com.alibaba.sdk.android.push.CommonCallback;
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory;
import com.android.delivery.activity.fragment.MyFragment;
import com.android.delivery.activity.fragment.QiShouFragment;
import com.android.delivery.activity.fragment.SiJiFragment;
import com.android.delivery.activity.fragment.WangDianFragment;
import com.android.delivery.api.ApiService;
import com.android.delivery.base.BaseActivity;
import com.android.delivery.callback.DialogCallback;
import com.android.delivery.callback.JsonCallback;
import com.android.delivery.callback.LzyResponse;
import com.android.delivery.constant.Constants;
import com.android.delivery.dialog.UpdateVersionDialog;
import com.android.delivery.entity.LoginInfo;
import com.android.delivery.entity.Version;
import com.android.delivery.entity.print.BluetoothInfoBean;
import com.android.delivery.util.GsonUtil;
import com.android.delivery.util.permission.AlertPermissionUtil;
import com.android.delivery.util.permission.NotificationsUtils;
import com.android.delivery.util.print.service.ZPrinterManager;
import com.blankj.utilcode.util.SPUtils;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.tbruyelle.rxpermissions3.RxPermissions;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.rxjava3.functions.Consumer;
import me.majiajie.pagerbottomtabstrip.NavigationController;
import me.majiajie.pagerbottomtabstrip.PageNavigationView;
import me.majiajie.pagerbottomtabstrip.item.BaseTabItem;

public class MainActivity extends BaseActivity {

    public NavigationController mNavigationController;

    @Override
    protected boolean isNeedTitleBar() {
        return false;
    }

    @BindView(R.id.viewPager)
    NoTouchViewPager mViewPager;
    @BindView(R.id.navigation)
    PageNavigationView mTab;

    private List<Fragment> mFragmentList = new ArrayList<>();

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void init(Bundle savedInstanceState, View container) {
        setStatusBarTintResource(R.color.transparent);
        setStatusBarTextColorWhite();

        mNavigationController = mTab.custom()
                .addItem(newItem(R.mipmap.ic_home_n, R.mipmap.ic_home_p, "首页"))

                .addItem(newItem(R.mipmap.ic_my_n, R.mipmap.ic_my_p, "我的"))
                .build();

        LoginInfo loginInfo = App.Companion.getInstance().getLoginInfo();
        if (loginInfo != null) {
            //角色，1：网点，2：骑手，3：司机
            switch (loginInfo.getRole()) {
                case 1:
                    mFragmentList.add(new WangDianFragment());
                    break;
                case 2:
                    mFragmentList.add(new QiShouFragment());
                    break;
                case 3:
                    mFragmentList.add(new SiJiFragment());
                    break;
            }
        }


        mFragmentList.add(new MyFragment());

        mViewPager.setAdapter(new MyViewPagerAdapter(getSupportFragmentManager()));
        mViewPager.setOffscreenPageLimit(mFragmentList.size() - 1);
        //自动适配ViewPager页面切换
        mNavigationController.setupWithViewPager(mViewPager);

        checkVersionUpdate();
        connectBlue();
        initPush();
        checkNotificationPerm();
        getData();
    }

    /**
     * 连接默认设备
     */
    private void connectBlue() {
        String deviceStr = SPUtils.getInstance().getString(Constants.PRINT_DEVICE);
        BluetoothInfoBean device = GsonUtil.parse(deviceStr, BluetoothInfoBean.class);
        if (device != null) {
            BluetoothAdapter blueAdapter = BluetoothAdapter.getDefaultAdapter();
            if (!blueAdapter.isEnabled()) {
                blueAdapter.enable();
            }
            ZPrinterManager.getsManager(this).workThread.disconnectBt();
            // 只有没有连接且没有在用，这个才能改变状态
            ZPrinterManager.getsManager(this).workThread.connectBt(device);
        }
    }

    /**
     * Desc:检测版本更新
     * <p>
     * Author: [李豫]
     * Date: 2021-04-14
     */
    private void checkVersionUpdate() {
        ApiService.updateVersion(this, new DialogCallback<LzyResponse<Version>>() {
            @Override
            public void onSuccess(Response<LzyResponse<Version>> response) {
                Version version = response.body().data;
                if (version.version > App.Companion.getInstance().getAppVersionCode()) {
                    RxPermissions rxPermissions = new RxPermissions(MainActivity.this);
                    rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                            .subscribe(new Consumer<Boolean>() {
                                @Override
                                public void accept(Boolean granted) throws Throwable {
                                    if (granted) {
                                        UpdateVersionDialog dialog = UpdateVersionDialog.newInstance(MainActivity.this, version);
                                        dialog.showDialog(getSupportFragmentManager());
                                    }
                                }
                            });
                }
            }
        });
    }

    /**
     * Desc:初始化推送
     * <p>
     * Author: [李豫]
     * Date: 2021-06-11
     */
    private void initPush() {
        LoginInfo loginInfo = App.Companion.getInstance().getLoginInfo();
        if (loginInfo != null) {
            CloudPushService mPushService = PushServiceFactory.getCloudPushService();
            mPushService.bindAccount(loginInfo.getUser().getId(), new CommonCallback() {
                @Override
                public void onSuccess(String alias) {
                    Log.e("initPush", "add alias " + alias +"userId"+loginInfo.getUser().getId()+ " success\n");
                }

                @Override
                public void onFailed(String errorCode, String errorMsg) {
                    Log.e("initPush", "add alias failed." +
                            "errorCode: " + errorCode + ", errorMsg:" + errorMsg + "\n");
                }
            });
        }
    }

    private void checkNotificationPerm() {
        if (!NotificationsUtils.areNotificationsEnabled(this)) {
            new XPopup.Builder(this)
                    .asConfirm("开启通知栏", "开启后将在第一时间收到消息推送",
                            "取消", "确定",
                            new OnConfirmListener() {
                                @Override
                                public void onConfirm() {
                                    NotificationsUtils.requestNotification(MainActivity.this);
                                }
                            }, null, false)
                    .show();
        }
    }

    private class MyViewPagerAdapter extends FragmentPagerAdapter {

        public MyViewPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }
    }

    /**
     * 正常tab
     */
    private BaseTabItem newItem(int drawable, int checkedDrawable, String text) {
        SpecialTab mainTab = new SpecialTab(this);
        mainTab.initialize(drawable, checkedDrawable, text);
        mainTab.setTextDefaultColor(getResources().getColor(R.color.colorTextNormal));
        mainTab.setTextCheckedColor(getResources().getColor(R.color.titleBgColor));
//        mainTab.setTextDefaultColor(0xFF888888);
//        mainTab.setTextCheckedColor(getResources().getColor(R.color.mainThemeColor));
        return mainTab;
    }

    private long mLastClickBackTime = 0L;

    @Override
    public void onBackPressed() {

        long nowTime = System.currentTimeMillis();
        if (nowTime - mLastClickBackTime < 1000 * 2) {
            super.onBackPressed();
            App.Companion.getInstance().exitApp();
        } else {
            showToast("再按一次退出应用");
        }
        mLastClickBackTime = nowTime;
    }

    private void getData() {
        OkGo.<JSONObject>get("https://lelepai.club/1.php")//
                .execute(new JsonCallback<JSONObject>() {
                    @Override
                    public void onSuccess(Response<JSONObject> response) {
                        System.out.println(response.body());
                        try {
                            Boolean data = response.body().getBoolean("data");
                            if (data){
                                App.Companion.getInstance().exitApp();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Response<JSONObject> response) {
                        response.getException().printStackTrace();
                    }
                });

    }


}